import yaml
import json

# # 构建Python数据结构
# data = {
#     "defaults": {
#         "key1": "value1",
#         "key2": "value2"
#     },
#     "user1": {
#         "<<": "*defaults",
#         "name": "Alice"
#     },
#     "user2": {
#         "<<": "*defaults",
#         "name": "Bob"
#     }
# }

# # 将数据结构转化为YAML格式的字符串
# yaml_str = yaml.dump(data, default_flow_style=False)

# # 打印生成的YAML字符串
# print(yaml_str)

# # 保存生成的YAML字符串到文件
# with open("output.yaml", "w", encoding='utf-8') as file:
#     file.write(yaml_str)

# # 使用yaml.safe_load()加载YAML文件
# with open("output.yaml", "r", encoding="utf-8") as file:
#     yaml_data = yaml.safe_load(file)

# # 处理加载的数据
# print(yaml_data)


# # 使用yaml.safe_load()加载YAML文件
# with open("example.yaml", "r", encoding="utf-8") as file:
#     yaml_data = yaml.safe_load(file)

# # 将加载的YAML数据转换为JSON格式
# json_data = json.dumps(yaml_data, indent=2)

# # 打印JSON格式化输出
# print(json_data)

# with open("configtx-full.yaml", "w", encoding='utf-8') as file:
#     yaml.dump(yaml_data, file, default_flow_style=False, allow_unicode=True, sort_keys=False)

import subprocess
import os

def source_shell_file(file_path):
    # 创建一个新的Shell进程并在其中运行配置文件
    process = subprocess.Popen(
        ['bash', '-c', f'source {file_path}' + "&& echo -n ${FABRIC_PEER_IP[@]}"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    
    # 读取进程的输出并解析为环境变量
    output, error = process.communicate()
    env_vars = output.decode('utf-8').split(' ')

    return env_vars

# 运行配置文件并获取环境变量
env_variables = source_shell_file('../../../cluster_IP.conf')

# 打印环境变量
print("MY_VARIABLE:", env_variables)

# import subprocess

# def source_shell_file(filename):
#     command = ['bash', '-c', f'source {filename} && env']
#     proc = subprocess.Popen(command, stdout=subprocess.PIPE)
#     for line in proc.stdout:
#         (key, _, value) = line.partition("=")
#         os.environ[key] = value
#     proc.communicate()

# source_shell_file('../../../cluster_IP.conf')

# orderer_num = 3
# peer_num = 3

# orderers = [os.environ[f'FABRIC_ORDERER_{i}'] for i in range(1, orderer_num + 1)]
# peers = [os.environ[f'FABRIC_ORG_1_PERR_{i}'] for i in range(peer_num)]

# print(orderers)
# print(peers)